<script setup lang="ts">
import {FormInstance, FormRules} from "element-plus";
import {useRuleInfoViewStore} from "@/store/views/sys/admin/ruleInfoStore";
import {RuleInfoType} from "@/api/sys/admin/rule-info/types";
import {addRuleInfoApi, editRuleInfoApi} from "@/api/sys/admin/rule-info";
import {OpenFormType, Perm} from "@/utils/enum-type";

const store = useRuleInfoViewStore()
const {getList, setVisible, title} = store
const {visible, formData, openFormType} = storeToRefs(store)
// 编辑表单时规则验证
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)
// 规则:适用于添加和修改
const rules: FormRules<RuleInfoType> = {
  title: [{required: true, message: '请输入标题', trigger: 'blur'}],
}

const addOrEditWord = openFormType.value === OpenFormType.Add ? '添加' : '修改'

// 提交新增
async function submit(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      let promise: Promise<any>
      if (openFormType.value === OpenFormType.Add) {
        promise = addRuleInfoApi(formData.value)
      } else {
        promise = editRuleInfoApi(formData.value.id, formData.value)
      }
      promise.then(async () => {
        loading.value = true
        await getList()
        ElMessage.success(`${addOrEditWord}成功`)
        setVisible(false)
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('错误的字段', fields)
    }
  })
}
</script>

<template>
  <!-- 添加对话框:添加 -->
  <el-dialog draggable v-model="visible" :title="`${addOrEditWord}${title}`" width="600" destroy-on-close>
    <el-form :model="formData" label-suffix=":" label-width="100" ref="ruleFormRef" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title"/>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <x-dict-select type-code="rule_info_type" v-model="formData.type" type="select"/>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input type="textarea" autosize v-model="formData.remark"/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort"/>
      </el-form-item>
      <el-form-item v-perm="Perm.SysRuleInfoStatus" label="状态" prop="status">
        <x-dict-select type-code="status" v-model="formData.status"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setVisible(false)">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>